package com.ycg.vue.utils;

import com.ycg.vue.config.EmailConfig;
import com.ycg.vue.modules.system.Entity.EmailEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.CompletableFuture;

/**
 * @Description
 * @Author jink
 * @Date 2024/8/20
 */
@Slf4j
@Component
public class EmailUtils extends EmailConfig {

    @Resource
    private JavaMailSender mailSender;

    @Async
    public CompletableFuture<Boolean> sent(EmailEntity email) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(this.USERNAME);
        message.setTo(email.getTo());
        message.setSubject(email.getSubject());
        message.setText(email.getContent());
        try {
            mailSender.send(message);
            return CompletableFuture.completedFuture(true);
        } catch (Exception e) {
            showError(e);
            return CompletableFuture.completedFuture(false);
        }
    }

    @Async
    public CompletableFuture<Boolean> sent(EmailEntity email, boolean isHtml) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            helper.setFrom(this.USERNAME);
            helper.setTo(email.getTo());
            helper.setSubject(email.getSubject());
            helper.setText(email.getContent(), isHtml);
            mailSender.send(mimeMessage);
            return CompletableFuture.completedFuture(true);
        } catch (Exception e) {
            showError(e);
            return CompletableFuture.completedFuture(false);
        }
    }

    public static final String CODE = "验证码";


    void showError(Exception e) {
        log.error("邮件发送失败");
        e.printStackTrace();
    }
}
